#include "WiiTextArea.h"

#ifdef LINUX
WiiTextArea::WiiTextArea(SDL_Surface* tscreen, TTF_Font* tfont, SDL_Color fcolor, int x, int y, int max_lines, int max_char_per_line, int line_space)
{
   MAX_LINES = max_lines;
   MAX_CHAR_PER_LINE = max_char_per_line;
   LINE_SPACE = line_space;
   x_loc = x;
   y_loc = y;
   screen = tscreen;
   font = tfont;
   color = fcolor;
   scroll_offset = 0;
}
#endif

#ifdef WII
WiiTextArea::WiiTextArea(int x, int y, int w, int h, Image* font):
textbox(w,h)
{
   textbox.SetPosition(x,y);
   textbox.SetFont(font);

   x_loc = x;
   y_loc = y;
   //screen = tscreen;
   //font = tfont;
   //color = fcolor;
   scroll_offset = 0;
}
#endif

WiiTextArea::~WiiTextArea()
{

}

void WiiTextArea::AddLine(std::string line)
{
   if(line.length() > 0)
      text.push_back(line);
}

void WiiTextArea::Append(std::string app_text)
{
   if(app_text.length() > 0)
      text.push_back(app_text);
}

void WiiTextArea::Clear()
{
   text.clear();
}

void WiiTextArea::ScrollUp(int lines)
{
   if(scroll_offset > 0) scroll_offset--;
}

void WiiTextArea::ScrollDown(int lines)
{
   if(text.size() > MAX_LINES && scroll_offset < (text.size() - MAX_LINES))
      scroll_offset++;
}

int WiiTextArea::Draw()
{
   int line_count = 0;
   int offset = scroll_offset;

   #ifdef LINUX
   int sIndex = text.size() - MAX_LINES-offset;

   if(sIndex < 0) sIndex = 0;
   for(int i=sIndex; i < text.size()-scroll_offset; i++)
   {
	   SDL_Surface *TTF_Message;
	   SDL_Rect loc;

           const char* str;
	   bool found = false;
	   int lBrack = 0;
	   int rBrack = 0;
	   int offset = 0;
	   std::string ret = "";

	   do{
	      lBrack = text.at(i).find("\n",offset);
              
              if(lBrack == -1) str = text.at(i).substr(offset,text.at(i).length()).c_str();
              else str = text.at(i).substr(offset,lBrack).c_str();

             if(str != NULL)
             {
                   #ifdef LINUX
		   if(!(TTF_Message = TTF_RenderText_Solid(font, str, color)))
		   {
		      SDL_FreeSurface(TTF_Message);
		      //printf("RenderText: Error trying to render text with TTF_(%s)\n",SDL_GetError());
		      //return 1;
		   }
                   else
                   {
			   loc.w = 0;
			   loc.h = 0;
			   loc.x = x_loc;
			   loc.y = y_loc+(LINE_SPACE*line_count);

			   line_count++;
			   SDL_BlitSurface(TTF_Message, 0, screen, &loc); 

			   SDL_FreeSurface(TTF_Message);
                    }
                   #endif
               }
	      offset = lBrack+1;
	   }while(lBrack != -1);

   }
   #endif
   #ifdef WII
   std::string txt = "";

   for(int i=0; i < text.size(); i++)
   {
      txt.append(text.at(i));
   }
   textbox.RenderText(txt.c_str());
   textbox.Draw();
   #endif
   return 0;
}
